//
//  MGTabPageView.m
//  QuickDev
//
//  Created by 胡超 on 2020/6/29.
//  Copyright © 2020 HuChao. All rights reserved.
//

#import "MGTabPageView.h"
#import "UIView+Mango.h"

@interface MGTabPageContentScrollView : UIScrollView
@end
@implementation MGTabPageContentScrollView

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (CGRectContainsPoint(CGRectMake(0, 0, 10, self.height), point)) {
        return nil;
    } else {
        return [super hitTest:point withEvent:event];
    }
}

@end

@interface MGTabPageView() <MGTabPageBarDelegate> {
    MGTabPageBarStyle *_barStyle;
    id _selectedPage;
}
@end

@implementation MGTabPageView

@synthesize pages = _pages;

- (void)dealloc {
    [self removeAllPages];
}

- (instancetype)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame style:nil];
}

- (instancetype)initWithFrame:(CGRect)frame style:(MGTabPageBarStyle *)style {
    if (self = [super initWithFrame:frame]) {
        [self _initialize:style];
        [self addSubview:_scrollView];
        [self addSubview:_tabPageBar];
    }
    return self;
}

- (void)_initialize:(MGTabPageBarStyle *)style {
    _pages = [NSArray array];
    _barStyle = style ?: [[MGTabPageBarStyle alloc] init];
    _barHeight = 44.0;
    
    _tabPageBar = [[MGTabPageBar alloc] initWithFrame:CGRectMake(0, 0, self.width, _barHeight) style:_barStyle];
    _tabPageBar.delegate = self;
    
    _scrollView = [[MGTabPageContentScrollView alloc] initWithFrame:CGRectMake(0, _barHeight, self.width, self.height-_barHeight)];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
}

- (void)setBarHeight:(CGFloat)barHeight {
    _barHeight = barHeight;
    _tabPageBar.height = barHeight;
    _scrollView.frame = CGRectMake(0, barHeight, self.width, self.height-barHeight);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.tabPageBar.size = CGSizeMake(self.width, _barHeight);
    self.scrollView.frame = CGRectMake(0, _barHeight, self.width, self.height-_barHeight);
    self.scrollView.contentSize = CGSizeMake(self.width*_pages.count, 0);
}

- (void)setPages:(NSArray *)pages titles:(NSArray<NSString *>*)titles parent:(UIViewController *)parent {
    [self removeAllPages];
    
    _pages = pages;
    _tabPageBar.items = titles;
    for (id page in pages) {
        if ([page isKindOfClass:UIViewController.class]) {
            [parent addChildViewController:page];
        }
    }
    // 设置初始选中状态
    [self setSelectedPageIndex:_selectedPageIndex animated:NO];
}

- (void)removeAllPages {
    if (_pages.count == 0)
        return;
    
    for (id page in _pages) {
        if ([page isKindOfClass:UIViewController.class]) {
            if ([page isViewLoaded]) {
                [[page view] removeFromSuperview];
            }
            [page removeFromParentViewController];
        } else {
            [page removeFromSuperview];
        }
    }
    _selectedPageIndex = 0;
    _pages = [NSArray array];
    _tabPageBar.items = nil;
    _scrollView.contentSize = CGSizeZero;
}

- (void)setSelectedPageIndex:(NSInteger)selectedPageIndex {
    [self setSelectedPageIndex:selectedPageIndex animated:YES];
}

- (void)setSelectedPageIndex:(NSInteger)selectedPageIndex animated:(BOOL)animated {
    _selectedPageIndex = selectedPageIndex;
    if (_selectedPageIndex < 0 || _selectedPageIndex >= _pages.count) {
        _selectedPageIndex = 0;
        return;
    }
    
    [self.tabPageBar setSelectedItemIndex:selectedPageIndex animated:animated];
    [self setScrollViewPageIndex:selectedPageIndex animated:animated];
}

- (void)setScrollViewPageIndex:(NSInteger)selectedPageIndex animated:(BOOL)animated {
    // 模拟viewController -[viewWillAppear:]
    void(^viewWillAppear)(id, BOOL) = ^(id page, BOOL animated) {
        if ([page isKindOfClass:[UIViewController class]]) {
            [page viewWillAppear:animated];
        }
    };
    // 模拟viewController -[viewDidAppear:]
    void(^viewDidAppear)(id, BOOL) = ^(id page, BOOL animated) {
        if ([page isKindOfClass:[UIViewController class]]) {
            [page viewDidAppear:animated];
        }
    };
    // 模拟viewController -[viewWillDisappear:]
    void(^viewWillDisappear)(id, BOOL) = ^(id page, BOOL animated) {
        if ([page isKindOfClass:[UIViewController class]]) {
            [page viewWillDisappear:animated];
        }
    };
    // 模拟viewController -[viewDidDisappear:]
    void(^viewDidDisappear)(id, BOOL) = ^(id page, BOOL animated) {
        if ([page isKindOfClass:[UIViewController class]]) {
            [page viewDidDisappear:animated];
        }
    };

    id prevPage = _selectedPage;
    viewWillDisappear(prevPage, animated);
    
    _selectedPage = _pages[selectedPageIndex];
    UIView *pageView = nil;
    if ([_selectedPage isKindOfClass:UIViewController.class]) {
        pageView = [_selectedPage view];
    } else {
        pageView = _selectedPage;
    }
    if (pageView.superview == nil) {
        pageView.frame = CGRectMake(self.width*selectedPageIndex, 0, self.width, self.scrollView.height);
        [self.scrollView addSubview:pageView];
        
        if ([self.delegate respondsToSelector:@selector(tabPageView:didAddPage:)]) {
            [self.delegate tabPageView:self didAddPage:_selectedPage];
        }
    } else {
        viewWillAppear(_selectedPage, animated);
    }
    
    [UIView animateWithDuration:animated ? 0.15 : 0.0 animations:^{
        self.scrollView.contentOffset = CGPointMake(self.width*selectedPageIndex, 0);
    } completion:^(BOOL finished) {
        viewDidDisappear(prevPage, animated);
        viewDidAppear(_selectedPage, animated);
    }];
    [self.scrollView endEditing:YES];
}

#pragma mark - MGTabControlDelegate

- (void)tabPageBar:(MGTabPageBar *)tabPageBar didSelectItemAtIndex:(NSInteger)atIndex {
    if (atIndex >= _pages.count) {
        return;
    }
    [self setScrollViewPageIndex:atIndex animated:YES];
    if ([self.delegate respondsToSelector:@selector(tabPageView:didSelectPageAtIndex:)]) {
        [self.delegate tabPageView:self didSelectPageAtIndex:atIndex];
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger pageIndex = scrollView.contentOffset.x / scrollView.frame.size.width;
    [self setSelectedPageIndex:pageIndex animated:YES];
}

@end

